package com.cy.uv.controller;

import com.cy.uv.DTO.OrderDTO;
import com.cy.uv.entity.Order;
import com.cy.uv.service.OrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;
    @GetMapping("/orderlist")
    ResponseEntity<?> getOrderByUsername(String username) {
        if (username == null) {
            return ResponseEntity.ok().body("您当前暂无订单，如有异常，请与管理员联系");
        }
            return ResponseEntity.ok(orderService.getOrderByUsername(username));
        }
    @Operation(summary = "订单创建")
    @ApiResponse(responseCode = "200", description = "下单成功")
    @GetMapping("/orderset")
    ResponseEntity<?> setOrder(OrderDTO orderDTO){
        Order order = new Order();
        //或许我需要一个DTO？但是怎么写？
        order.setProduct_name(orderDTO.getProductName());
        order.setUserName(orderDTO.getUsername());
        /*order.setOrderDate(orderDTO.getOrderDate());*/
        order.setStatus(orderDTO.getStatus());
        order.setBill( (orderDTO.getPrice()) * (orderDTO.getQuantity()) );
        order.setQuantity(orderDTO.getQuantity());
        try {
            orderService.save(order);
        }
        catch (Exception e) {
            return ResponseEntity.badRequest().body("下单失败，请检查网络，或者再试一次");
        }
        return ResponseEntity.ok().body("下单成功");
    }
    @Operation(summary = "订单支付，feign交给pay调用")
    @ApiResponse(responseCode = "200", description = "订单支付成功")
    @DeleteMapping("/orderfinish")
    ResponseEntity<?> finishOrder(Integer orderId) {
        try {
            orderService.removeById(orderId);
        }
        catch (Exception e) {
            return ResponseEntity.badRequest().body("订单支付失败，请再试一次");
        }
        return ResponseEntity.ok().body("订单支付成功");
    }

    @Operation(summary = "取消订单")
    @GetMapping("/orderdel")
    ResponseEntity<?> deleteOrder(int orderId) {
        if (orderService.orderisOK(orderId)==1 )//如果支付成功
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("订单已经成功支付，不可取消");

        try {
            Order order = orderService.getById(orderId);
            order.setStatus(2);
        }
        catch (Exception e) {
            return ResponseEntity.badRequest().body("订单取消失败，请再试一次或联系管理员");
        }
        return ResponseEntity.ok().body("订单取消成功");
    }
}
